import { useModel } from 'umi';
import { get_platformuser_select } from '@/services/patient';
import { warning_list, warning_processed } from '@/services/sickbeds';
import { InfoCircleTwoTone } from '@ant-design/icons';
import { ActionType, PageContainer, ProColumns, ProTable } from '@ant-design/pro-components'
import { Button, Divider, Modal, Tooltip, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react'
import { ws } from '@/utils/webSocket';

type GithubIssueItem = {
    phone: string;
    id: number;
    name: string;
    sex: string;
    birth: string;
    id_card: string;
    address: number;
    create_time: string;
    bind_doctor: [{ id: number; username: string }];
    info_status: number;
    province: string;
    city: string;
    area: string;
    family_address: string;
};
function isValidJSON(text: any) {
    try {
        let result = JSON.parse(text);
        return result;
    } catch (error) {
        return false;
    }
}
const CallReminder = () => {

    const actionRef = useRef<ActionType>();
    // 存储处理确认模态框的状态
    const [isModalOpen, setIsModalOpen] = useState(false)
    // 存储当前记录id
    const [id, setId] = useState<number>()
    // 存储责任医生下拉框数据
    const [doctors, setDoctors] = useState<any>([]);
    const { setCount, sickbedWarningVisible, setsickbedWarningVisible } = useModel('SickbedWarningModel', (model) => ({
        setCount: model.setCount,
        sickbedWarningVisible: model.sickbedWarningVisible,
        setsickbedWarningVisible: model.setsickbedWarningVisible
    }));


    // 控制处理确认模态框的显示与隐藏
    const isShowModalOpen = (status: boolean) => {
        setIsModalOpen(status)
    }

    // 页面初始化
    useEffect(() => {
        console.log('CallReminder加载完成');

        // // 监听消息 收到呼叫刷新当前页面
        // ws.onmessage = (message: any) => {
        //     console.log('呼叫提醒页面', message.data);
        //     const result = isValidJSON(message.data)
        //     if (result) {
        //         if (result.type == 'sickbedWarning') {
        //             //刷新当前列表
        //             actionRef.current?.reload();
        //         }
        //     }
        // };
        // 获取责任医生下拉列表
        const getDoctorList = async () => {
            let res = await get_platformuser_select();
            let arr: any = [];
            res.data.map((item: { id: number; username: any }) => {
                arr[item.id] = { text: item.username };
            });
            setDoctors(arr);
            console.log('责任医生', arr);
        };
        getDoctorList();
        setsickbedWarningVisible(false);
    }, []);
    // 监听消息 收到呼叫刷新当前页面
    ws.onmessage = (message: any) => {
        console.log('wwwwwwwwwwwwwwwwwwwwwwwwww:', message.data);
        const result = isValidJSON(message.data)
        if (result) {
            if (result.type == 'sickbedWarning') {
                //刷新当前列表
                actionRef.current?.reload();
            }
        }
    };

    // 获取呼叫提醒列表
    const get_warning_list = async (params: {
        pageSize?: number | undefined;
        current?: number | undefined;
        keyword?: string | undefined;
    }) => {
        //默认分页参数和后端接口字段不匹配
        let request_body = {
            ...params,
            current: params.current,
            pageSize: params.pageSize,
        };
        let res = await warning_list(request_body)
        console.log('呼叫提醒列表', res);
        return {
            data: res.data.list,
            success: true,
            total: res.data.total_count,
        };
    }
    // 确认处理的回调
    const handleOk = async () => {
        let request_body = {
            id: id,
        };
        const res: any = await warning_processed(request_body);
        if (res.msg == 'ok') {
            message.success('处理成功');
            actionRef.current?.reload();
        } else {
            message.error(res.msg);
        }
        setIsModalOpen(false);
    };
    // 呼叫提醒列表字段
    const columns: ProColumns<GithubIssueItem>[] = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'index',
            hideInSearch: true,
            align: 'center',
        },
        {
            title: '病床编号',
            dataIndex: 'sickbed_code',
            align: 'center',
        },
        {
            title: "患者",
            key: 'patient_name',
            dataIndex: 'patient_name',
            align: 'center'
        },
        {
            title: '手机号',
            key: 'patient_phone',
            dataIndex: 'patient_phone',
            align: 'center',
            hideInSearch: true
        },
        {
            title: '责任医生',
            dataIndex: 'bind_doctor',
            key:'bind_doctor',
            hideInSearch: true,
            align: 'center',
            render: (_, record) => (
                <Tooltip title={record.bind_doctor.map((item: any) => item.username).join()}>
                    {record.bind_doctor.map((item: any) => item.username).join().length > 5
                        ? record.bind_doctor
                            .map((item: any) => item.username)
                            .join()
                            .substring(0, 5) + '...'
                        : record.bind_doctor.map((item: any) => item.username).join()}
                </Tooltip>
            ),
        },
        {
            title: '责任医生',
            dataIndex: 'doctor_id',
            key:'doctor_id',
            hideInTable: true,
            align: 'center',
            valueType: 'select',
            valueEnum: doctors,
            fieldProps: {
                showSearch: true,
                filterOption: (input: any, option: any) =>
                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            },
        },
        {
            title: '呼叫时间',
            dataIndex: 'create_time',
            align: 'center',
            hideInSearch: true,
        },
        {
            title: "状态",
            key: 'status',
            dataIndex: 'status',
            align: 'center',
            hideInSearch: true,
            valueEnum: {
                0: {
                    text: "待处理"
                },
                1: {
                    text: "已处理"
                }
            }
        },
        {
            title: '操作',
            hideInSearch: true,
            align: 'center',
            render: (_: any, record: any) => (
                <>
                    <Button
                        key="agree"
                        type="link"
                        onClick={() => {
                            setId(record.id)
                            isShowModalOpen(true)
                        }}
                        disabled={record.status == 0 ? false : true}
                    >
                        已处理
                    </Button></>
            )
        },
    ];
    return (
        <PageContainer breadcrumb={false}>
            <ProTable<GithubIssueItem>
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params = {}) => get_warning_list(params)}
                editable={{
                    type: 'multiple',
                }}
                rowKey={(record) => record.id}
                search={{
                    labelWidth: 'auto',
                    collapseRender: false,
                    collapsed: false,
                    span: 6,
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                pagination={{
                    pageSize: 10,
                }}
                dateFormatter="string"
                headerTitle="呼叫提醒列表"
            />
            {/* 处理弹窗提醒 */}
            <Modal
                title="处理确认"
                open={isModalOpen}
                onOk={handleOk}
                onCancel={() => isShowModalOpen(false)}
            >
                <Divider />
                <p>
                    <InfoCircleTwoTone twoToneColor="#ffcc00" /> 确定已通过语音或视频联系患者吗？
                </p>
            </Modal>
        </PageContainer>
    )
}
export default CallReminder